package com.qf.order.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.qf.order.domain.dto.OrderExcelDTO;
import com.qf.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class OrderImportListener implements ReadListener<OrderExcelDTO> {

    // 批量处理阈值
    private static final int BATCH_COUNT = 100;

    // 临时存储
    private List<OrderExcelDTO> cachedDataList = new ArrayList<>(BATCH_COUNT);

    // 订单服务
    private OrderService orderService;

    // 必须提供无参构造器
    public OrderImportListener() {}

    // 用于传入service
    public OrderImportListener(OrderService orderService) {
        this.orderService = orderService;
    }

    // 每读取一行数据都会调用
    @Override
    public void invoke(OrderExcelDTO data, AnalysisContext context) {
        log.info("读取到一条订单数据: {}", data);
        cachedDataList.add(data);

        // 达到BATCH_COUNT，需要去存储一次数据库，防止数据几万条在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList.clear();
        }
    }

    // 所有数据读取完成后调用
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有订单数据解析完成！");
    }

    // 批量保存数据
    private void saveData() {
        log.info("开始保存 {} 条订单数据", cachedDataList.size());
        if (!cachedDataList.isEmpty() && orderService != null) {
            orderService.batchImport(cachedDataList);
        }
        log.info("订单数据保存完成！");
    }
}
